<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogFormVisible"
    width="500px"
    @close="close"
  >
    <el-form ref="form" label-width="80px" :model="form" :rules="rules">
      <el-form-item label="姓名" prop="customer_name">
        <el-input v-model="form.customer_name" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="联系方式" prop="customer_mobile">
        <el-input v-model="form.customer_mobile" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="证件号" prop="customer_idcard">
        <el-input
          v-model="form.customer_idcard"
          placeholder="请输入身份证号"
          @input="changeIdcard"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { isPhone, isIdCard } from '@/utils/validate'
  export default {
    name: 'AddTogether',
    data() {
      const validatePhone = (rule, value, callback) => {
        if (!isPhone(value)) {
          callback(new Error('请输入正确的手机号'))
        } else {
          callback()
        }
      }
      const validateIdCard = (rule, value, callback) => {
        if (value && !isIdCard(value)) {
          callback(new Error('请输入正确的身份证号'))
        } else {
          callback()
        }
      }
      return {
        form: {
          customer_type: 2,
          customer_name: '',
          customer_mobile: '',
          customer_idcard: '',
        },
        rules: {
          customer_name: [
            { required: true, trigger: 'blur', message: '请输入姓名' },
          ],
          customer_mobile: [
            { required: true, trigger: 'blur', message: '请输入手机号' },
            { validator: validatePhone, trigger: 'blur' },
          ],
          customer_idcard: [{ validator: validateIdCard, trigger: 'change' }],
        },
        title: '添加同住人',
        dialogFormVisible: false,
      }
    },
    methods: {
      async showEdit() {
        this.dialogFormVisible = true
      },
      changeIdcard(e) {
        if (e == '') {
          setTimeout(() => {
            this.$refs['form'].clearValidate('customer_idcard')
          }, 200)
        }
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
      },
      save() {
        let e = Object.assign({}, this.form)
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.$baseMessage('添加成功', 'success', 'vab-hey-message-success')
            this.$emit('fetch-data', e)
            this.close()
          }
        })
      },
    },
  }
</script>
